from fastapi import APIRouter, Depends
from sqlalchemy.ext.asyncio import AsyncSession

from apps.system import schemas
from apps.system.cruds import UserDal, MenuDal, DictDal
from apps.models import SysUser
from apps.system.utils.login_manage import LoginManage
from apps.system.utils.validation import LoginForm
from core.auth import FullAdminAuth, Auth
from core.database import db_getter
from core.exceptions import CustomException
from core.response import SuccessResponse

router = APIRouter()


@router.post("/user/login", summary="用户登录")
async def login(
        data: LoginForm,
        db: AsyncSession = Depends(db_getter)
):
    user = await UserDal(db).get_data(username=data.username, v_return_none=True)
    if not user:
        raise CustomException(status_code=200, code=401, msg="账号不存在")
    result = SysUser.verify_password(data.password, user.password)
    if not result:
        raise CustomException(status_code=200, code=401, msg="账号或密码错误")
    if not user.is_active:
        raise CustomException(status_code=200, code=401, msg="账号已经被冻结")
    token = LoginManage.create_token({"username": user.username})
    resp = {"token": token}
    return SuccessResponse(resp)


@router.post("/user/logout", summary="用户登出")
async def logout(
        auth: Auth = Depends(FullAdminAuth())
):
    # todo: token存入缓存后，从redis删除token
    return SuccessResponse()


@router.get("/user/info", summary="获取当前用户管理信息")
async def get_user_admin_current_info(
        auth: Auth = Depends(FullAdminAuth())
):
    result = schemas.UserOut.model_validate(auth.user).model_dump()
    menus = await MenuDal(auth.db).get_routers(auth.user)
    dicts = await DictDal(auth.db).get_dicts_details_options()
    result["permissions"] = list(FullAdminAuth.get_user_permissions(auth.user))
    result["menus"] = menus
    result["dicts"] = dicts
    return SuccessResponse(result)
